package cn.caskm.souvenirshopsystem.utils;

import cn.hutool.crypto.asymmetric.RSA;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JwtUtil {

    public static String createToken(Map<String, Object> map, String privateKey, long dateOffset) {
        RSA rsa = new RSA(privateKey, null);
        Map<String, Object> header = new HashMap<>();
        header.put("type", "jwt");
        header.put("author", "schandfanfan");
        header.put("alg", SignatureAlgorithm.RS256.getValue());
        return Jwts.builder()
                .setHeader(header)
                .signWith(rsa.getPrivateKey(), SignatureAlgorithm.RS256)
                .setClaims(map)
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * dateOffset))
                .compact();
    }

    public static Claims parseToken(String token, String publicKey) {
        RSA rsa = new RSA(null, publicKey);
        try {
            return Jwts.parserBuilder()
                    .setSigningKey(rsa.getPublicKey())
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }

    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", 1);
        String token = createToken(map,
                "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCXYkk5kSeqilE24gnwxCtSoVxzvp5U9x20mF3BmEMbI4U7VvF0K1ddXC5ne6Tip7BUai6hm/VGhmesUkTxCgoU9LkGtBqatyHskeGDmYLzjeEm8OF5ZVXwyAzh792/mjqrquXbxfJZdYdK7gFyE7xdpEQY1ssj436ztYukkPatD3FIQ6IJiBV5dRV0tADgaZrrbUPm5KOcUdjC4l+eyjBBQa3wGC+lrW9qpQe96SgnmPnRiHQB5V2tJ1//FTJG/8hCZivKZDBDGmDEYkJlbB0k6Mmj3g6cuFCVCEOVPlVUZndPZF9JXwIbI9PX/M0BSifrRWvnk4zwUtAzX9AqieZ9AgMBAAECggEBAJPTCiYItG83+e5Z89MD/DoID7uGnB3j4UI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eciAF9HZanadqMypDEUN4GLPjBinMR8mphD0MMtLPQdAySfFdmUp+ToMSxOYr6gYh1RUIzl2E5h2rN4vORPThcFIPj/0YHn2yTT7c73DcJ9CG9iyCVDQ==",
                30);
        Claims claims = parseToken(token,
                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAl2JJOZEnqopRNuIJ8MQrUqFcc76eVPcdtJhdwZhDGyOFO1bxdCtXXVwuZ3uk4qewVGouoZv1RoZnrFJE8QoKFPS5BrQamrch7JHhg5mC843hJvDheWVV8MgM4e/dv5o6q6rl28XyWXWHSu4BchO8XaREGNbLI+N+s7WLpJD2rQ9xSEOiCYgVeXUVdLQA4Gma621D5uSjnFHYwuJfnsowQUGt8Bgvpa1vaqUHvekoJ5j50Yh0AeVdrSdf/xUyRv/IQmYrymQwQxpgxGJCZWwdJOjJo94OnLhQlQhDlT5VVGZ3T2RfSV8CGyPT1/zNAUon60Vr55OM8FLQM1/QKonmfQIDAQAB");
        Object userId = claims.get("userId");
        System.out.println(userId);
    }

}
